import 'dart:async';
import 'dart:io';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/custom_length_limiting_text_input_formatter.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

/// 品牌或门店名称
class SmartHomeTitlePage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeTitlePage";
  //标题
  final String brandName;
  final String storeName;
  final String id;

  const SmartHomeTitlePage(
      {Key key, this.brandName, this.storeName, this.id}) : super(key:key);

  @override
  _SmartHomeTitlePageState createState() => _SmartHomeTitlePageState();

  static Future<Map> navigatorPush(BuildContext context, String id, {String brandName, String storeName,}){
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomeTitlePage(
          brandName: brandName,
          storeName: storeName,
          id: id,
        ),
        routeName: SmartHomeTitlePage.ROUTER
    );
  }
}

class _SmartHomeTitlePageState
    extends BaseState<SmartHomeTitlePage> {

  TextEditingController _titleController;
  //指示牌标题
  String _title = "";
  String _originTitle = "";
  SmartHomeViewModel _viewModel;

  String _pageTitle = "品牌名称";
  String _hint= "请输入（10字以内）";
  int _limit = 10;

  @override
  void initState() {
    super.initState();
    _viewModel = SmartHomeViewModel(this);
    if(StringUtils.isNotEmpty(widget?.brandName??"")){
      _title = widget?.brandName;
      _originTitle = _title;
      _titleController = TextEditingController(text: _title);
      _pageTitle = "品牌名称";
      _hint = "请输入（10字以内）";
      _limit = 10;
    }else if(StringUtils.isNotEmpty(widget?.storeName??"")){
      _title = widget?.storeName;
      _originTitle = _title;
      _titleController = TextEditingController(text: _title);
      _pageTitle = "门店名称";
      _hint = "如：居然之家十里河店";
      _limit = 10;
    }else{
      _titleController = TextEditingController();
    }
  }

  @override
  void dispose() {
    _titleController.clear();
    _titleController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        _toSmartHomeTitleWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: _pageTitle??"品牌或门店名称",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toSaveButtonWidget(),
    );
  }

  Widget _toSaveButtonWidget() {
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: isCanSave(),
      width: 48,
      height: 24,
      unSelectBgColor:Color(0xFFCFD4DB),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
          color: Colors.white,
          fontSize: 12,
          fontWeight: FontWeight.w600),
      selectedTextStyle: TextStyle(
          color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
      text: "保存",
      onTap: (){
        _save();
      },
    );
  }

  void _save(){
    if(!isCanSave()){
      return;
    }
    // if(StringUtils.isEmpty(widget?.id)){
    //   _viewModel.createStore(context, _title.trim(), null,
    //       null,null,null,null,null,null,
    //       (String id){
    //     Map map={'title': _title.trim(), 'id': id};
    //     RouterUtils.pop(context, result: map);
    //   });
    // }else{
    //   _viewModel.editStoreName(context, widget?.id, _title.trim());
    // }
    if(StringUtils.isNotEmpty(widget?.brandName??"")){
      _viewModel.editBrandName(context, widget?.id, _title.trim());
    }else if(StringUtils.isNotEmpty(widget?.storeName??"")){
      _viewModel.editStoreName(context, widget?.id, _title.trim());
    }else{
      _viewModel.editBrandName(context, widget?.id, _title.trim());
    }
  }

  ///标题
  Widget _toSmartHomeTitleWidget(){
    return Container(
      height: 50,
      color: Colors.white,
      child: Container(
        height: 50,
        padding: EdgeInsets.symmetric(horizontal: 15),
        child: Container(
          alignment: Alignment.centerLeft,
          child: VgTextField(
            controller: _titleController,
            keyboardType: TextInputType.text,
            autofocus: true,
            textAlign: TextAlign.left,
            style: TextStyle(
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                fontSize: 14),
            decoration: new InputDecoration(
                counterText: "",
                hintText: _hint??"请输入（16字以内）",
                border: InputBorder.none,
                hintStyle: TextStyle(
                    fontSize: 14,
                    color: Color(0XFFB0B3BF))),
            maxLines: 1,
            maxLimitLength: Platform.isAndroid?_limit:null,
            zhCountEqEnCount: true,
            limitCallback:(int){
              Platform.isAndroid?VgToastUtils.toast(context, "最多可输入${_limit}个字"):{};
            },
            onChanged: (value){
              // int position = CustomLengthLimitingTextInputFormatter.getMaxLimtCharPositionForStr(value,
              //     maxLimitCount: _limit, zhCountEqEnCount: true);
              // if(position != null && position > 0){
              //   _titleController?.text = value.substring(0, _limit);
              //   _titleController.selection = TextSelection.fromPosition(TextPosition(
              //       affinity: TextAffinity.downstream,
              //       offset: _limit));
              //   VgToastUtils.toast(context, "最多可输入${_limit}个字");
              // }
              _notifyChange();
            },
          ),
        ),
      ),
    );
  }

  ///通知更新
  _notifyChange() {
    _title = _titleController?.text?.trim();
    if(_title.length > _limit){
      _title = _title.substring(0, _limit);
    }
    setState(() { });
  }

  bool isCanSave(){
    //没有内容
    if(StringUtils.isEmpty(_title)){
      return false;
    }
    //与原来内容相同
    if(_title.trim() == _originTitle.trim()){
      return false;
    }
    return true;
  }


}
